package com.example.myproject.easyexcel;

import java.io.FileOutputStream;
import java.util.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
//poi 3.17
public class EasyExcelTest {

    static class SheetWriteHandlerUtil implements SheetWriteHandler {

        private final String title;
        private final String[] header;

        public SheetWriteHandlerUtil(String title, String[] header) {
            this.title = title;
            this.header = header;
        }

        @Override
        public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

        }

        @Override
        public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
//            Workbook workbook = writeWorkbookHolder.getWorkbook();
//            Sheet sheet = workbook.getSheetAt(0);
//            //设置标题
//            Row row1 = sheet.createRow(0);
//            row1.setHeight((short) 800);
//            Cell cell = row1.createCell(0);
//            //设置单元格内容
//            cell.setCellValue(title);
//            CellStyle cellStyle = workbook.createCellStyle();
//            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//            cellStyle.setAlignment(HorizontalAlignment.CENTER);
//            Font font = workbook.createFont();
//            font.setBold(true);
//            font.setFontHeight((short) 400);
//            cellStyle.setFont(font);
//            cell.setCellStyle(cellStyle);
//            // 第一行大标题占位设置
//            sheet.addMergedRegionUnsafe(new CellRangeAddress(0, 0, 0, header.length-1));
        }
    }

    public static WriteCellStyle getHeadStyle(){
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("黑体");//设置字体名字
        headWriteFont.setFontHeightInPoints((short)15);//设置字体大小
        headWriteFont.setBold(true);//字体加粗
        headWriteCellStyle.setWriteFont(headWriteFont); //在样式用应用设置的字体;
        // 样式
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
        headWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);  //设置左边框;
        headWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
        headWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
        headWriteCellStyle.setTopBorderColor((short) 0); //设置顶边框颜色;
        headWriteCellStyle.setWrapped(true);  //设置自动换行;
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//设置水平对齐的样式为居中对齐;
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);  //设置垂直对齐的样式为居中对齐;
        //        headWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适

        return headWriteCellStyle;
    }

    public static void main(String[] args) throws  Exception {
        String[] header = {"宿舍","姓名"};
        String fileName = "实时离寝情况报表";

        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("dorm","123");
        map.put("stuName","456");
        list.add(map);
        map.put("dorm","33");
        map.put("stuName","333");
        list.add(map);

        // 标题样式
        WriteCellStyle headWriteCellStyle = getHeadStyle();
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
        FileOutputStream fos  =   new FileOutputStream("d:/323.xls");
        EasyExcel.write(fos)
                // 第一行大标题样式设置
               // .registerWriteHandler(new SheetWriteHandlerUtil(fileName))
                //设置默认样式及写入头信息开始的行数
                //.useDefaultStyle(true).relativeHeadRowIndex(1)
                // 表头、内容样式设置
                //.registerWriteHandler(horizontalCellStyleStrategy)
                // 统一列宽,如需设置自动列宽则new LongestMatchColumnWidthStyleStrategy()
                //.registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                .sheet(fileName)
                // 这里放入动态头
                .head(head(header,fileName))
                // 当然这里数据也可以用 List<List<String>> 去传入
                .doWrite(detail(list));
               fos.close();
    }
    /**动态头传入*/
    public static List<List<String>> head(String[] header, String bigTitle) {
        List<String> head0 = null;
        List<List<String>> list = new LinkedList<List<String>>();
        for (String h : header) {
            head0 = new LinkedList<>();
            head0.add(bigTitle);
            head0.add(h);
            list.add(head0);
        }
        return list;
    }

    private static  List<List<Object>> detail(List<Map<String,Object>> mapList) {
        List<List<Object>> list =  new ArrayList<List<Object>>();
        for (Map<String, Object> map : mapList) {
            List<Object> objectList = new ArrayList<>();
            objectList.add(map.get("dorm"));
            objectList.add(map.get("stuName"));
            //objectList.add("789");
            list.add(objectList);
        }
        return list;
    }

//    /**
//     * 导出晨午检信息
//     * @param response
//     * @throws Exception
//     */
//    @RequestMapping(value = "exportMorningCheck")
//    public void exportMorningCheck(){
//
//        if(StringUtils.isEmpty(rec.getKdgId()))
//        {
//            return;
//        }
//        StringBuffer bigTitle = new StringBuffer();
//        if(StringUtils.isEmpty(rec.getMorningCheckTime()) || rec.getMorningCheckTime().length() == 0){
//            rec.setMorningCheckTime(DateUtils.format(new Date(),"yyyy-MM-dd"));
//            bigTitle.append(DateUtils.format(new Date(),"yyyy年MM月dd日"));
//        }else{
//            Date date = DateUtils.parseDate(rec.getMorningCheckTime(),"yyyy-MM-dd");
//            bigTitle.append(DateUtils.format(date,"yyyy年MM月dd日"));
//        }
//
//        List<HealthCheckMorningCheckRec> morningCheckList = healthCheckMorningCheckRecService.getMorningCheckRecInfo(rec);
//
//        if(morningCheckList != null && morningCheckList.size() > 0){
//            bigTitle.append(morningCheckList.get(0).getKdgName());
//        }
//
//        bigTitle.append("晨午检详单");
//
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode(bigTitle.toString(), "UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//
//
//        // 头的策略
//        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//
//        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
//
//        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//
//        EasyExcel.write(response.getOutputStream(), MorningCheckExcelModel.class).head(getMorningCheckHead(bigTitle.toString()))
//                .registerWriteHandler(horizontalCellStyleStrategy).sheet("晨午检").doWrite(getMorningCheckData(morningCheckList));
//    }
//
//    /**
//     * 获取晨午检信息
//     * @return
//     */
//    private List<MorningCheckExcelModel> getMorningCheckData(List<HealthCheckMorningCheckRec> checkList){
//        List<MorningCheckExcelModel> data = new ArrayList<>();
//        for(HealthCheckMorningCheckRec rec : checkList){
//            MorningCheckExcelModel model = new MorningCheckExcelModel();
//            model.setCheckTime(rec.getMorningCheckTime());
//            model.setClassName(rec.getClassName());
//            model.setRemark(rec.getParComp());
//            model.setSymptom(rec.getCheckException());
//            model.setTemp(rec.getMorningCheckTemp() + "℃");
//            model.setName(rec.getChildName());
//            data.add(model);
//        }
//        return data;
//    }
//
//    public static WriteCellStyle getHeadStyle(){
//        // 头的策略
//        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//        // 背景颜色
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//        // 字体
//        WriteFont headWriteFont = new WriteFont();
//        headWriteFont.setFontName("黑体");//设置字体名字
//        headWriteFont.setFontHeightInPoints((short)15);//设置字体大小
//        headWriteFont.setBold(true);//字体加粗
//        headWriteCellStyle.setWriteFont(headWriteFont); //在样式用应用设置的字体;
//        // 样式
//        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
//        headWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
//        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);  //设置左边框;
//        headWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
//        headWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
//        headWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
//        headWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
//        headWriteCellStyle.setTopBorderColor((short) 0); //设置顶边框颜色;
//        headWriteCellStyle.setWrapped(true);  //设置自动换行;
//        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//设置水平对齐的样式为居中对齐;
//        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);  //设置垂直对齐的样式为居中对齐;
//        //        headWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适
//
//        return headWriteCellStyle;
//    }

}
